package com.yeyks.getui.service;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.yeyks.base.Arguments;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fuchangshuai
 * @date 2019/4/11 2:50 PM
 */
@Component
@Slf4j
public class GeTuiService {

    @Value("${getui.config.appId}")
    private String appId;
    @Value("${getui.config.masterSecret}")
    private String masterSecret;
    @Value("${getui.config.appKey}")
    private String appKey;
//    @Value("${getui.config.url}")
//    private String url;

    private IGtPush push;

    @PostConstruct
    public void init() {
//        push = new IGtPush(url, appKey, masterSecret);
        push = new IGtPush(appKey, masterSecret, false);
    }

    /**
     * 个推推送(给指定用户推)
     *
     * @param userId
     * @param title
     * @param content
     */
    public void singlePush(String userId, String title, String content) {
        if (!Arguments.notEmpty(userId)) {
            log.info("推送用户不能为空userId");
            return;
        }
        TransmissionTemplate template = linkTemplateDemo(title, content);
        SingleMessage message = new SingleMessage();
        //消息离线是否存储
        message.setOffline(true);
        //消息离线存储多久，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        //推送消息消息内容
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        //别名推送方式
        target.setAlias(userId);
        IPushResult ret;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            log.info("给指定用户推{}", e.getLocalizedMessage());
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            log.info("给指定用户推{}", ret.getResponse().toString());
        } else {
            log.info("给指定用户推{}", "服务器响应异常");
        }
    }

    /**
     * 个推推送(给指定多个用户推)
     *
     * @param userIds
     * @param title
     * @param content
     */
    public void morePush(List<String> userIds, String title, String content) {
        if (userIds == null || userIds.size() == 0) {
            log.info("推送用户不能为空userIds");
            return;
        }
        TransmissionTemplate template = linkTemplateDemo(title, content);
        ListMessage message = new ListMessage();
        //消息离线是否存储
        message.setOffline(true);
        //消息离线存储多久，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        //推送消息消息内容
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        List<Target> targets = getTarget(userIds);
        String taskId = push.getContentId(message);
        IPushResult ret;
        try {
            ret = push.pushMessageToList(taskId, targets);
            log.info("给多个用户推{}", ret.getResponse().toString());
        } catch (RequestException e) {
            log.info("给多个用户推异常{}", e.getLocalizedMessage());
        }
    }

    /**
     * 个推推送(给所有用户推)
     *
     * @param title
     * @param content
     */
    public void allPush(String title, String content) {
        TransmissionTemplate template = linkTemplateDemo(title, content);
        AppMessage message = new AppMessage();
        //推送消息消息内容
        message.setData(template);
        //消息离线是否存储
        message.setOffline(true);
        //消息离线存储多久，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        List<String> appIdList = new ArrayList<>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);
        // 1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        //手机类型
        List<String> phoneTypeList = new ArrayList<>();
        //省份
        List<String> provinceList = new ArrayList<>();
        //自定义tag
        List<String> tagList = new ArrayList<>();
        cdt.addCondition(AppConditions.PHONE_TYPE, phoneTypeList);
        cdt.addCondition(AppConditions.REGION, provinceList);
        cdt.addCondition(AppConditions.TAG, tagList);
        message.setConditions(cdt);
        IPushResult ret;
        try {
            ret = push.pushMessageToApp(message);
            log.info("给所有用户推{}", ret.getResponse().toString());
        } catch (RequestException e) {
            log.info("给所有用户推异常{}", e.getLocalizedMessage());
        }
    }

    private List<Target> getTarget(List<String> userIds) {
        List<Target> targets = new ArrayList<>();
        for (String userId : userIds) {
            Target target = new Target();
            target.setAlias(userId);
            target.setAppId(appId);
            targets.add(target);
        }
        return targets;
    }

    private TransmissionTemplate linkTemplateDemo(String title, String content) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);
        //内容
        template.setTransmissionContent(content);
        APNPayload apnPayload = new APNPayload();
        apnPayload.setAutoBadge("+1");
        apnPayload.setCategory("$由客户端定义");
        //标题
        apnPayload.setAlertMsg(new APNPayload.SimpleAlertMsg(title));
        template.setAPNInfo(apnPayload);
        return template;
    }

}
